/**
 * 
 */
package com.fsharemobile.client;

import java.io.IOException;

import android.os.AsyncTask;

/**
 * @author RAD-Dungtm9
 *
 */

public class APICallTask extends AsyncTask<Object, Void, HttpResponse> {

	private OnAPICallCompleted listener;
	
	private HttpUtil httputil;		

	public APICallTask(HttpUtil httputil, OnAPICallCompleted onAPICallCompleted) {
		this.listener = onAPICallCompleted;
		this.httputil = httputil;		
	}

	@Override
	protected HttpResponse doInBackground(Object... params) {
		for (int i = 0; i < 5; i++) {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		// System.out.println(params[0]);
		HttpRequest request = null;
		request = (HttpRequest)params[0];		
		HttpResponse response = null;		
		try {
			//result = get(new URL(params[0]));			
			if (request.getBody() == null) {
				response = httputil.get(request);
			} else {				
				response = httputil.post(request);
			}		
		} catch (IOException ex) {
			System.out.println(ex.toString());
		}		

		return response;
	}

	@Override
	protected void onPostExecute(HttpResponse result) {
		// TextView txt = (TextView) findViewById(R.id.output);
		// txt.setText("Executed"); // txt.setText(result);
		// might want to change "executed" for the returned string passed
		// into onPostExecute() but that is upto you
		listener.onAPICallCompleted(result);
	}

	@Override
	protected void onPreExecute() {
	}

	@Override
	protected void onProgressUpdate(Void... values) {
	}
	
	public interface OnAPICallCompleted {
		void onAPICallCompleted(HttpResponse result);
	}

}